﻿using _4_NovaAdmin.Web.Core.IM;
using _4_NovaAdmin.Web.Core.Option;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_NovaAdmin.Web.Core.Middlewares
{
    public static class ImServerMiddleware
    {
        public static IApplicationBuilder UseImServer(this IApplicationBuilder app)
        {
            ImUtility im = app.ApplicationServices.GetRequiredService<ImUtility>();
            // 启用 WebSocket 支持
            app.UseWebSockets();
            // Map 方法：用于将请求路径映射到特定的中间件管道
            // options.PathMatch：指定IM服务器的路径前缀，例如 /im，这样所有以 /im 开头的请求都会被这个中间件处理
            app.Map(im.imOptions.PathMatch, appcur =>
            {
                appcur.Use(async (ctx, next) =>
                {
                    var imserv = new ImServer(im);
                    await imserv.Acceptor(ctx, next);
                });
            });

            im.OnSend += (s, e) =>
                Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonConvert.SerializeObject(e.Message)})");

            im.EventBus(
                t =>
                {
                    Console.WriteLine(t.clientId + "上线了");
                    var onlineUids = im.GetClientListByOnline();
                    im.SendMessage(t.clientId, onlineUids, $"用户{t.clientId}上线了");
                },
                t => Console.WriteLine(t.clientId + "下线了"));

            return app;
        }
    }


}
